// $Id: GanttChart.java 90 2011-08-09 17:03:08Z jchimene@gmail.com $

package com.systasis.sked.client.view;

import java.util.ArrayList;
import java.util.Collection;

import com.arcetis.gwt.jsgantt.client.GanttChartListener;
import com.arcetis.gwt.jsgantt.client.TaskItem;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;

public class GanttChart extends Widget {
    public static final String GANTT_CHART_D_I_V = "GanttChartDIV";
    private static GanttChart instance = null;

    public static GanttChart create() {
	if (instance == null) {
	    final JavaScriptObject jso = GanttChartImpl.create();
	    GanttChartImpl.setShowResTrue(jso);
	    GanttChartImpl.setShowDurTrue(jso);
	    GanttChartImpl.setShowCompTrue(jso);
	    instance = new GanttChart(DOM.getElementById(GANTT_CHART_D_I_V));
	    instance.ganttChartJS = jso;
	}

	return instance;
    }

    private GanttChartListener ganttChartListener;

    JavaScriptObject ganttChartJS;
    Collection<TaskItem> taskItems = new ArrayList<TaskItem>();

    GanttChart(Element element) {
	super();
	this.setElement(element);
    }

    public final void addTaskItem(TaskItem taskItem) {
	taskItems.add(taskItem);
	GanttChartImpl.addTaskItem(ganttChartJS, taskItem);
    }

    public final GanttChart clear(Widget chart) {
	chart.removeFromParent();
	Element e = Document.get().getElementById(GANTT_CHART_D_I_V);
	if (null != e) {
	    e.setInnerHTML(null);
	}
	e = Document.get().createDivElement();
	e.setId(GANTT_CHART_D_I_V);
	Document.get().getDocumentElement().appendChild(e);
	instance = null;
	return null;
    }

    public final void generate() {
	draw();
	drawDependencies();

	if (ganttChartListener != null) {
	    // add listener to new tasks
	    for (final TaskItem taskItem : taskItems) {
		final ClickListener clickListener = new TaskItemClickListenerImpl(ganttChartListener, taskItem);
		taskItem.addListerner(clickListener);
	    }
	    // clear
	    taskItems.clear();
	}
    }

    public GanttChartListener getGanttChartListener() {
	return ganttChartListener;
    }

    public void setGanttChartListener(GanttChartListener ganttChartListener) {
	this.ganttChartListener = ganttChartListener;
    }

    private final void draw() {
	GanttChartImpl.draw(ganttChartJS);
    }

    private final void drawDependencies() {
	GanttChartImpl.drawDependencies(ganttChartJS);
    }
}
